package com.wt.springboot.demo.myendpoint;

import com.wt.springboot.demo.myendpoint.anno.MyEndPoint;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.handler.AbstractHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangtao
 * @date 2023/2/27 20:09
 **/
public class MyEndpointHandlerMapping extends AbstractHandlerMapping {

    /**
     * 请求路径到方法的映射
     */
    private Map<String, MyEndpointHandlerMethod> mappings = new HashMap<>();

    @Override
    protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
        // 根据请求的路劲，返回对应的处理方法
        return mappings.get(request.getServletPath());
    }

    public void initMappings() {
        Map<String, Object> beansWithAnnotation = obtainApplicationContext().getBeansWithAnnotation(MyEndPoint.class);
        // 遍历所有的bean，注册对应的mapping
        beansWithAnnotation.forEach((beanName, bean) -> {
            MyEndPoint clzAnno = bean.getClass().getAnnotation(MyEndPoint.class);
            // 只处理public方法的
            Arrays.stream(bean.getClass().getDeclaredMethods()).forEach(method -> {
                MyEndPoint anno;
                if ((anno = method.getAnnotation(MyEndPoint.class)) != null) {
                    // 创建路径到方法的映射
                    mappings.put(clzAnno.path() + anno.path(), new MyEndpointHandlerMethod(method, bean));
                }
            });

        });
    }

    @Override
    public int getOrder() {
        // 设置最高优先级
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
